
<%@page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %>
<%@include file="/common/common.jsp"%>
<%@include file="/common/skins/skin0/component.jsp" %>
<h:css href="/css/style1/style-custom.css"/>

<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>
      换房
    </title>    
    <script type="text/javascript" src="commonPick/script/utils.js"></script> 
    
    <script>
      //配置参数
      <% int ic = 0; %>
      gCfg = {
      <l:iterate property="cfg" id="id1">
         <% if (ic > 0){%>
         ,
         <%} %>
         '<b:write property="parameterCode" iterateId="id1"/>':'<b:write property="parameterValue" iterateId="id1"/>'
         <%ic++; %>
      </l:iterate>
      };
      
      //折扣规则
      <%ic=0; %>
      gRules = [
         <l:iterate property="rules" id ="id2">
         <% if (ic > 0){%>
         ,
         <%} %>
         {
           cCategory:'<b:write property="ccategory" iterateId="id2"/>',
           ndaysfrom:<b:write property="ndaysfrom" iterateId="id2"/>,
           ndaysto:<b:write property="ndaysto" iterateId="id2"/>,
           nratediscount:<b:write property="nratediscount" iterateId="id2"/>
         }
         <%ic++; %>
         </l:iterate>
      ];
      
    </script>   
               
  </head>
  <body>             
    <h:form name="data_form" action="com.hms.OrderMgr.changeRoom.flow" method="post" onsubmit="return submitDatacell(this);">
      <h:hidden property="oldgres/igresid" />
      
      <input type="hidden" name="_eosFlowAction" value="changroom" >      
      <dataform>
          <table align="center" border="0" width="100%" class="form_table">
            <tr>
               <td class="form_label">
                  新房号
               </td>
              <td style="color:blue">
                 <w:lookup lookupUrl="com.hms.commonPick.WeRoomSelect.flow"
                           dialogTitle="选择房间"
                           id="gresid"
                           allowInput="false"
                           displayProperty="gres/roomo"
                           property="gres/iroomid"  
                           onReturnFunc="setRoom"
                           validateAttr="allowNull=false"                        
                           style="width:200px;"/><font style="color:red">*</font>
              </td>               
              <td class="form_label">
                入住日期
              </td>
              <td colspan="1">
                <w:date property="gres/arrorigdate" onSelectFunc="setDate"  style="width:120px;" allowInput="false"  format="yyyy-MM-dd HH:mm:ss" /><font style="color:red">*</font>
              </td>
              <td class="form_label">
                离店日期
              </td>
              <td colspan="1">
                <w:date property="gres/deporigdate" onSelectFunc="setDate"   style="width:120px;" allowInput="false"  format="yyyy-MM-dd HH:mm:ss" /><font style="color:red">*</font>
              </td>
            </tr>
            <tr>
               <td class="form_label">
                  换房原因
               </td>
              <td colspan="5" style="color:blue">
                <h:textarea property="gres/cdescription" style="width:780px;"  validateAttr="allowNull=false"       /><font style="color:red">*</font>
                <h:hidden property="errCode"/>
                <h:hidden property="errMsg"/>                
              </td>               
            </tr> 
          </table>
      </dataform>
      
      <r:datacell height="250" pageSize="1000" entityType="com.hms.OrderMgr.order.WeRoomrateSchedule" id="schedule"  submitXpath="gres/schedules" width="100%" xpath="gres/schedules">
        <r:toolbar location="top" tools="eidt:info"/>
        <r:field fieldName="dbusinessdate" width="200" label="入住日期"/>
        <r:field fieldName="nrate" width="200" label="房价"/>
      </r:datacell>
      
      <table align="center" border="0" width="100%" class="form_table">
            <tr class="form_bottom">
              <td colspan="4" class="form_bottom">
                <input type="submit" value="确定" class="button">
                <input type="button" value="关闭" class="button">                
              </td>
            </tr>
          </table>
    </h:form>
    <script>
      function submitDatacell(frm) {
        if ($name("errCode").value == "E"){
          alert($name("errMsg").value);
          return false;
        }
                            
        if (checkForm(frm)) {
          
          var arrdate = $name("gres/arrorigdate").value||"",
              depdate = $name("gres/deporigdate").value || "",
              roomno = $id("gresid_input").value || "";
              
          if (!trim(arrdate)){
            alert("抵店日期不能为空!");
            return false;
          }
          
          if (!trim(depdate)){
            alert("离店店日期不能为空!");
            return false;
          }
                    
          var x = stringToDate(arrdate, 'yyyy-MM-dd HH:mm:ss').getTime(), y = stringToDate(depdate, 'yyyy-MM-dd HH:mm:ss').getTime();
          if (x > y){
            alert("预计抵店日期必须小于预计离店日期");
            return false;        
          }
      
          var m = new Date();
          if (x < m.getTime() - 30000){
           alert("预计抵店日期必须大于当前日期");
           return false;        
          }
          
          if (y < m.getTime() - 30000){
            alert("预计离店日期必须大于当前日期");
            return false;        
          }   
                  
          var dcell = $id('schedule'); 
          
          dcell.submitAllByHidden();
          return true;
        }

        return false;
      }

      function loadSchedule(xroomId, xstartDate, xendDate, xgresId, roomno){
        var x1 = toBusinessDate(stringToDate(xstartDate,'yyyy-MM-dd HH:mm:ss')), 
            x2 = toBusinessDate(stringToDate(xendDate, 'yyyy-MM-dd HH:mm:ss')),
            x = {roomId:xroomId,
                 startDate:dateToString(x1),
                 endDate:dateToString(x2),
                 dayCount:((x2.getTime() - x1.getTime() + 1 * 24 * 60 * 60 * 1000) / 3600000 / 24),
                 memberId:'<b:write property="memberId"/>',
                 gresId:xgresId?xgresId:''
                 };
            if (x1.getTime() > x2.getTime()){
              alert("预计离店日期必须大于等于抵店日期!");
              return;
            }
        jrq(function(a){
          calGressSchedule(eval("(" + a + ")"), xroomId, xstartDate, xendDate, null, roomno);
        }, 
        "POST", 
        JSON.stringify(x), 
        "com.hms.OrderMgr.priceUtils.queryRoomRate.biz.ext", 
        false);
      
      }
      
      
      //获取已经维护的某个日期的实体
      function getScheduleByDate(bdate, ety){
        for(var i = 0; i < ety.length; i++){
          if (ety[i].getPropertyByFieldName("dbusinessdate") == bdate){
            return ety[i];
          }
        }
        return null;
      }

      //计算客单房租计划
      function calGressSchedule(schedule, srcRoomId, srcFrom, srcTo, key, roomno){
        
        //判断房间是否被占用,如果被占用就设置错误标志
        if (schedule.errCode == "E"){   
          var x = "房号" + roomno + '在指定日期范围内已经被客单' + schedule.errMsg + '占用，不能预订!';
          $name("errCode").value = "E";
          $name("errMsg").value = x;
          alert(x);
          return;
        }
        
        $name("errCode").value = "";
        $name("errMsg").value = "";
        
        //删除超出日期范围的数据
        var sches = $id("schedule").dataset,
            schEty = $id("schedule").dataset.getAlltEntities(),
            bSrcTo = dateToString(toBusinessDate(stringToDate(srcTo, 'yyyy-MM-dd HH:mm:ss'))),
            bSrcFrom = dateToString(toBusinessDate(stringToDate(srcFrom, 'yyyy-MM-dd HH:mm:ss')));
        if (schEty != null){
           for(var i = schEty.length -1; i >= 0; i--){
             if (schEty[i].getPropertyByFieldName("dbusinessdate") > bSrcTo || schEty[i].getPropertyByFieldName("dbusinessdate") < bSrcFrom){
               sches.removeEntity(schEty[i], true);
             }
           }
        }
      
        var vFrom = stringToDate(bSrcFrom, 'yyyy-MM-dd').getTime(), 
            vTo = stringToDate(bSrcTo, 'yyyy-MM-dd').getTime(),
            vDate = stringToDate(bSrcFrom, 'yyyy-MM-dd');
            count = 0;
            
        while (vFrom <= vTo){
           var vBDate = stringToDate(bSrcFrom, 'yyyy-MM-dd');
           vBDate.setDate(vDate.getDate() + count);
           
           //从返回的房价信息中获取房价或标准房价
           var p = getPrice(dateToString(vBDate), schedule, bSrcFrom, bSrcTo);
           p.iroomid = srcRoomId;
           p.cstatus = 'B';
           
           //检查是否存在
           var sEty = getScheduleByDate(dateToString(vBDate, 'yyyy-MM-dd'), schEty);
           if (!sEty){
              sches.addEntity(Json2Entity(p));
           }else{
              sEty.setProperty("nroomrate", p.nroomrate);
              sEty.setProperty("nratedisount", p.nratedisount);     
              sEty.setProperty("nmemberdiscount", p.nmemberdiscount);   
              sEty.setProperty("commisionRate", p.commisionRate);                    
           }
           
           count++;
           vFrom += 1 * 24 * 60 * 60 * 1000;
        }
        
        $id("schedule").refresh(); 
      }
      
      //从价目表中获取房价、折扣、佣金等信息
      function getPrice(busiDate, list, vstart, vend){
        var result = {nroomrate:0, 
                      nrate:0, 
                      nroomrate:0,
                      ncommissionprice:0, 
                      nratedisount:0, 
                      nmemberdiscount:0,
                      dbusinessdate:busiDate}, 
            found = false;
            
            
        //算标准房价
        for(var i = 0; i < list.rates.length; i++){
          if (list.rates[i].dbusinessdate == busiDate){
            found = true;
            result.nroomrate = Number(list.rates[i].nroomrate);
            break;
          }
        }
        
        if (found == false){
          result.nroomrate = Number(list.basePrice);
        }else if (list.rates[i].bisdiscount == "Y"){
            //从折扣表中查找数据，计算折扣--包括天数折扣和价格折扣
            getNewDiscount(result, dayDiff(vstart, vend), result.nroomrate, list.charge);
        }
        
        result.nroomrate = Math.round(result.nroomrate * (1 - result.nratedisount) * (1 - result.nmemberdiscount) * 10000) / 10000;
        result.nrate  = result.nroomrate;
        if (list.commisionRate){
          result.ncommissionprice = Math.round(result.nrate * (gCfg && gCfg.commisionRate ? gCfg.commisionRate:list.commisionRate) * 10000)/10000;
        }
        
        return result;
      }
      
      //从折扣规则中检查折扣
      function getNewDiscount(priceInfo, vDays, vAmount, memcharge){
      
        //取天数折扣
        var discount = 2;
        for(var i = 0; i < gRules.length; i++){
          if (gRules[i].cCategory == "M"){continue;}
          if (vDays >= gRules[i].ndaysfrom && vDays <= gRules[i].ndaysto && discount > gRules[i].nratediscount){
            discount = gRules[i].nratediscount;
          }
        }
        
        if (discount != 2){
          priceInfo.nratedisount = discount;
        }
        
        //取会员折扣
        discount = 2;
        for(var i = 0; i < gRules.length; i++){
          if (gRules[i].cCategory != "M"){
            continue;
          }
          
          if (memcharge >= gRules[i].ndaysfrom && memcharge <= gRules[i].ndaysto && discount > gRules[i].nratediscount){
            discount = gRules[i].nratediscount;
          }
        }
        
        if (discount != 2){
          priceInfo.nemberDiscount = discount;
        }
      }
      
      //取日期间的距离
      function dayDiff(start, end){
        var x1 = toBusinessDate(stringToDate(start, 'yyyy-MM-dd HH:mm:ss')).getTime(), 
            x2 = toBusinessDate(stringToDate(end, 'yyyy-MM-dd HH:mm:ss')).getTime();
            
        if (x1 > x2){return "";}
        
        var result = 0;
        while (x1 <= x2){
          result++;
          x1 += 1 * 24 * 60 * 60 * 1000;
        }
        
        return result;
      }
      
      //将自然日期转换为营业日期(不带时分秒)
      function toBusinessDate(date){
        var year =  date.getFullYear(),
            month = date.getMonth();
            day = date.getDate(),
            target = new Date(year, month, day, 12, 0, 0);
        
        if (date.getTime() > target.getTime()){//如果是12点钟之后，就划入当前营业日期
          return new Date(year, month, day);  
        }else{//如果划入前一个营业日期
          var down = new Date(date.getTime() - 24 * 60 * 60*1000);
          return new Date(down.getFullYear(), down.getMonth(), down.getDate());
        }
      }
       
      function setRoom(args){
         if (args[0] == '<b:write property="oldgres/igresid"/>'){
          var x = "不能换成当前房间，请重新选择";
          alert(x);
          return false;
         }
         
         refreshSchedule(args[0]);
         
         return true;     
      }
      
      function setDate(){
        try{
          refreshSchedule();
        }catch(e) {
          alert(e)
        }
        
      }
            
      function refreshSchedule(vroom){
        var roomid = vroom || $name("gres/iroomid").value || "",
            arrdate = $name("gres/arrorigdate").value||"",
            depdate = $name("gres/deporigdate").value || "",
            roomno = $id("gresid_input").value || "";
        
         if (!trim(roomid) || !trim(arrdate) || !trim(depdate)){
           return;
         }   
         loadSchedule(roomid, arrdate, depdate, null, roomno);
      }

      <l:notEmpty property="gres/igresid">
        var ret = new Array;
        ret[0] = '<b:write property="gres/igresid"/>';
        window.returnValue = ret;
        window.close();        
      </l:notEmpty>
    </script>
  </body>
  

  
</html>

